package com.yeqian.utils;


import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

/**
 * 文件上传工具类
 *
 * @author yeqian
 * @return
 * @date 2020/12/22 10:54
 */
public class OSSUtils {

    //配置连接
    private static final String ENDPOINT = "";//外网访问节点
    private static final String ACCESSKEYID = "";//id
    private static final String ACCESSKEYSECRET = "";//密钥
    //private static String BUKETINAME = "20200724";//仓库名称
    // private static String SUFFER_URL = "https://20200724.oss-cn-beijing.aliyuncs.com/";//上传成功返回的url
    private static String BUKETINAME = "";//仓库名称
    private static String SUFFER_URL = "https://仓库名称.oss-cn-beijing.aliyuncs.com/";//上传成功返回的url

    /**
     * 创建oss连接对象
     *
     * @return
     */
    public static OSSClient getOSSClient() {
        OSSClient ossClient = new OSSClient(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET);
        //判断仓库是否存在
        if (ossClient.doesBucketExist(BUKETINAME)) {
            System.out.println("buket创建成功");

        } else {
            System.out.println("buket不存在，创建bucket：" + BUKETINAME);
            //创建一个OSS库
            CreateBucketRequest bucketRequest = new CreateBucketRequest(null);
            //设置仓库名称
            bucketRequest.setBucketName(BUKETINAME);
            //设置权限为公共读
            bucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(bucketRequest);
        }
        return ossClient;
    }

    /**
     * 列举指定存储空间下的文件
     */
    public static List<String> GetBucketV2(String Prefix) {
        OSSClient ossClient = getOSSClient();
        List<String> list = new LinkedList<>();
        // 列举文件。如果不设置KeyPrefix，则列举存储空间下的所有文件。如果设置KeyPrefix，则列举包含指定前缀的文件。
        // 列举包含指定前缀的文件。默认列举100个文件。
        ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(BUKETINAME).withPrefix(Prefix));
        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
        for (OSSObjectSummary s : sums) {
            list.add(s.getKey());
            //System.out.println("\t" + s.getKey());
        }
        // 关闭OSSClient。
        ossClient.shutdown();
        return list;
    }


    /**
     * 删除单个文件
     *
     * @param fileURL
     */
    public static void deleteFile(String fileURL) {
        OSSClient ossClient = getOSSClient();
        // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
      // tag/2021/01/09f866a189-f7ad-4e53-9867-faeb12f93139.jpg
        ossClient.deleteObject(BUKETINAME, fileURL);
        //删除成功 打印文件存储地址
        System.out.println("delete success");
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    /**
     * 上传文件
     *
     * @param multipartFile 需要上传的文件
     * @return
     */
    public static String upload(MultipartFile multipartFile, String path) {
        OSSClient ossClient = getOSSClient();
        //获取文件的后缀名称
        String ext = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        //上传至oss的images文件夹
        //为了避免图片重名，使用UUid来命名图片
        String uuid = UUID.randomUUID().toString();
        //组合filename
        //String filename = "images/" + uuid + ext;
        String filename = path + uuid + ext;
        String url = null;
        //通过osscllient来获取上传文件后返回的url
        try {
            ossClient.putObject(BUKETINAME, filename, new ByteArrayInputStream(multipartFile.getBytes()));
            url = SUFFER_URL + filename;
            System.out.println("------>上传成功，oss地址为：" + url);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        return url;//http://20200724.oss-cn-beijing.aliyuncs.com/ae006c9d-be04-42dc-8b4d-72bafcc9063f.jpg
    }

    /**
     * 获取存储空间的访问权限
     *
     * @return void
     * @author yeqian
     * @date 2020/12/20 23:32
     */
    public static void getRole() {
        OSSClient ossClient = getOSSClient();
        // 获取存储空间的访问权限。
        AccessControlList acl = ossClient.getBucketAcl(BUKETINAME);
        System.out.println(acl.toString());
    }

    /**
     * 设置访问权限为公共读
     */
    public static void setRole4PublicRead() {
        OSSClient ossClient = getOSSClient();
        ossClient.setBucketAcl(BUKETINAME, CannedAccessControlList.PublicRead);
    }

    /**
     * 设置访问权限为私有
     */
    public static void setRole4Private() {
        OSSClient ossClient = getOSSClient();
        // 设置存储空间的访问权限为私有。
        ossClient.setBucketAcl(BUKETINAME, CannedAccessControlList.Private);
    }

    /**
     * 设置访问权限为公共读写
     */
    public static void setRole4PublicReadWrite() {
        OSSClient ossClient = getOSSClient();
        // 设置存储空间的访问权限为私有。
        ossClient.setBucketAcl(BUKETINAME, CannedAccessControlList.PublicReadWrite);
    }
}
